<template>
  <div v-loading="treeLoading">
    <el-input placeholder="输入关键字进行过滤"
              v-model="filterText"
              clearable />
    <el-tree ref="treeRef"
             class="tree"
             show-checkbox
             default-expand-all
             node-key="id"
             highlight-current
             :data="data"
             :check-strictly="checkStrictly"
             :filter-node-method="filterNode"
             :props="{
                children: 'children',
                label: 'name'
              }" />
  </div>
</template>

<script>
export default {
  name: 'PowerTree',
  props: {
    powerArray: Array
  },
  data () {
    return {
      treeLoading: false,
      data: [],
      checkStrictly: false,
      filterText: ''
    }
  },
  watch: {
    filterText (val) {
      this.$refs.treeRef.filter(val)
    }
  },
  methods: {
    getPowerTree () {
      this.treeLoading = true
      const config = {
        url: '/sysPower/tree',
        method: 'get'
      }
      this.$axios(config)
        .then(res => {
          this.data = res.data
          this.treeLoading = false
          this.setTreeData()
        })
        .catch(() => {
          this.treeLoading = false
        })
    },
    filterNode (value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    setCheckedKeys (arr) { // 设置选中节点
      this.$refs.treeRef.setCheckedKeys(arr)
    },
    getCheckedKeys () { // 获取选中节点
      return this.$refs.treeRef.getCheckedKeys()
    },
    setTreeData () {
      setTimeout(() => {
        this.powerArray.forEach((i, n) => {
          var node = this.$refs.treeRef.getNode(i)
          if (node && node.isLeaf) {
            this.$refs.treeRef.setChecked(node, true)
          }
        })
      }, 100)
    }
  }
}
</script>
<style scoped>
.el-tree {
  background: transparent !important;
}
</style>
